<?php 

class suipaiController extends appController
{
	private $configUlr = "Mobile/Config/pay.json";
	public function index()
	{
		$page = yf_empty(intval($_GET['page']), 1, true);
		$sort['c'] = yf_empty($_GET['c'], '', true);
		$sort['k'] = yf_empty($_GET['k'], '', true);
		
		
		$list = Model('suipai')->get_list($sort, $page);
		$this->assign('ad_list', $list['data']);
		$this->assign('user_list_page', $list['pagelink']);
// 		var_dump($list['data']);
		$this->display("index.html");
	}
	
	public function picture()
	{
		$page = yf_empty(intval($_GET['page']), 1, true);
		$sort['c'] = yf_empty($_GET['c'], '', true);
		$sort['k'] = yf_empty($_GET['k'], '', true);
	
	
		$list = Model('suipai')->get_pic_list($sort, $page);
		$this->assign('ad_list', $list['data']);
		$this->assign('user_list_page', $list['pagelink']);
		// 		var_dump($list['data']);
		$this->display("picture.html");
	}
	
	public function ordering()
	{
		$id = yf_empty(intval($_POST['id']), '', true);
		$val = yf_empty(intval($_POST['val']), '', true);
		$result = Model('suipai')->ordering($val, $id);
		$this->showMsg($result);
	}
	

	public function del()
	{
		$id=isset($_REQUEST['id'])?$_REQUEST['id']:'';
	
		if(is_array($id))
		{
			foreach($id as $k=>$v)
			{
				$result=Model('suipai')->del_sp($v,"suipai");
			}
		}
		else
		{
			$id=intval($id);
	
			$result=Model('suipai')->del_sp($id,"suipai");
		}
		print_r(json_encode($result));
	
	}
	
	public function del_pic()
	{
		$id=isset($_REQUEST['id'])?$_REQUEST['id']:'';
	
		if(is_array($id))
		{
			foreach($id as $k=>$v)
			{
				$result=Model('suipai')->del_pic($v);
			}
		}
		else
		{
			$id=intval($id);
	
			$result=Model('suipai')->del_pic($id);
		}
		print_r(json_encode($result));
	
	}
	
	
	public function del_code()
	{
	    $id=isset($_REQUEST['id'])?$_REQUEST['id']:'';
	
	    if(is_array($id))
	    {
	        foreach($id as $k=>$v)
	        {
	            $result=Model('suipai')->del_code($v);
	        }
	    }
	    else
	    {
	        $id=intval($id);
	
	        $result=Model('suipai')->del_code($id);
	    }
	    print_r(json_encode($result));
	
	}
	
	
	public function prince(){
		$page=isset($_REQUEST['page'])?intval($_REQUEST['page']):1;
// 		$startTime = isset($_REQUEST['startTime'])?strtotime($_REQUEST['startTime']):mktime(0,0,0,date("m"),date("d"),date("Y"));
// 		$endTime = isset($_REQUEST['endTime'])?strtotime($_REQUEST['endTime']):0;
		$startTime = isset($_REQUEST['startTime'])?$_REQUEST['startTime']:0;
		$endTime = isset($_REQUEST['endTime'])?$_REQUEST['endTime']:0;
		$nickname = isset($_REQUEST['nickname'])?$_REQUEST['nickname']:'';
		$out_trade_no = isset($_REQUEST['out_trade_no'])?$_REQUEST['out_trade_no']:'';
		$transaction_id = isset($_REQUEST['transaction_id'])?$_REQUEST['transaction_id']:'';
		$status = isset($_REQUEST['status'])?$_REQUEST['status']:0;
		if($startTime!=0){
			$total['startTime'] = $startTime;
		}
		if($endTime!=0){
			$total['endTime'] = $endTime;
		}
		$total['nickname'] = $nickname;
		$total['out_trade_no'] = $out_trade_no;
		$total['transaction_id'] = $transaction_id;
		if($status!=0){
			$total['status'] = $status;
		}
		$list=Model('suipai')->list_record($page,$total);
		$this->assign('sql_list',$list['data']);
		$this->assign('list_page',$list['pagelink']);
		$total['count'] = $list['count'];
		$total['pass_count'] = $list['pass_count'];
		$total['nopass_count'] = $list['nopass_count'];
		$total['passing_count'] = $list['passing_count'];
		$this->assign('total',$total);
		$this->assign('page',$page);
		$this->display('wx_pay_record.html');
	}
	
	public function saveTransaction(){
		$transaction = $_POST['transaction'];
		$id = $_POST['id'];
		$path = ROOT_PATH.$this->configUlr;
		$json = json_decode(file_get_contents($path), true);
		$nonce_str = hy_rand(16);
		$signData = array(
				"appid"  			=> $json['appid'],
				"mch_id" 			=> $json['mch_id'],
				"nonce_str"			=> $nonce_str,
				"transaction_id" 	=> $transaction,
		);
		ksort($signData);
		$stringA = $this->ToUrlParams($signData)."&key=".$json['key'];
		$sign=strtoupper(md5($stringA));
		$signData['sign'] = $sign;
		$str = "<xml>
		<appid>$signData[appid]</appid>
		<mch_id>$signData[mch_id]</mch_id>
		<nonce_str>$signData[nonce_str]</nonce_str>
		<transaction_id>$signData[transaction_id]</transaction_id>
		<sign>$signData[sign]</sign>
		</xml>";
		$url = "https://api.mch.weixin.qq.com/pay/orderquery";
		$result=$this->post_it($url, $str);
				$result=(array)simplexml_load_string($result, 'SimpleXMLElement', LIBXML_NOCDATA);
				if($result['return_code']=="SUCCESS"&&$result['result_code']=="SUCCESS"){
						if($result['trade_state'] =="SUCCESS"){
							$info = Model('suipai')->get_order($id);
							if($info['openid']!=$result['openid']){
								$res['error'] = 1;
								$res['content'] = "该订单用户与提交的微信号订单用户不是同一个";
								die(json_encode($res));
							}
							if($info['total_fee']!=$result['total_fee']){
								$res['error'] = 1;
								$res['content'] = "该订单金额与提交的微信号订单金额不符合";
								die(json_encode($res));
							}
							if($info['out_trade_no']!=$result['out_trade_no']){
								$res['error'] = 1;
								$res['content'] = "该订单与提交的微信订单信息不符合";
								die(json_encode($res));
							}
							$order['transaction_id'] = $transaction;
							$order['pay_status'] = "SUCCESS";
							Model('suipai').update($order,array('table'=>"wx_pay","id"=>$id));
							$res['error'] = 0;
							die(json_encode($res));
						}else{
							$res['error'] = 1;
							$res['content'] = "提交的微信订单号未付款";
							die(json_encode($res));
						}
				}
				$res['error'] = 1;
				$res['content'] = "提交的微信订单号有问题";
				die(json_encode($res));
	}
	public function ToUrlParams($values){
		$buff = "";
		foreach ($values as $k => $v)
		{
			if($k != "sign" && $v != "" && !is_array($v)){
				$buff .= $k . "=" . $v . "&";
			}
		}
		$buff = trim($buff, "&");
		return $buff;
	}
	
	
	public function code()
	{
	    
	    $page = yf_empty(intval($_GET['page']), 1, true);
	    
	    
	    $list = Model('suipai')->get_code_list($page);
	    $this->assign('code_list', $list['data']);
	    $this->assign('code_list_page', $list['pagelink']);
	    // 		var_dump($list['data']);
	    $this->display("code.html");
	}
	
	
	public function editCode()
	{
	    if($_POST)
	    {
	        $info = $_POST;
	        $result = array('error' => 1,'content' => '');
	        
	        if(Model('suipai')->checkCode($info))
	        {
	            $result['content'] = "邀请码已存在";
	        }
	        elseif(!$info['name']||!$info['codes']||!$info['money'])
	        {
	            $result['content'] = "信息不完整";
	        }
	        elseif(Model('suipai')->insertRecord($info,"wx_pay_code"))
	        {
	            $result['error'] = 0;
	            $result['content'] = Lang('VALID_OPERATION');
	        }
	        else
	        {
	            $result['content'] = Lang('INVALID_OPERATION');
	        }
	        $this->showMsg($result);
	    }
	    else
	    {
	        
    	    $this->display('editCode.html');
	    }
	    
	}
	
	
	public function saveSetting()
	{
	    $this->admin_priv($_GET['type'], 2);
	    $info = $_POST;
	    $result = array('error' => 1,'content' => '');
	    if(Model('sys')->saveSetting($info))
	    {
	        $result['error'] = 0;
	        $result['content'] = Lang('VALID_OPERATION');
	    }
	    else
	    {
	        $result['content'] = Lang('INVALID_OPERATION');
	    }
	    $this->showMsg($result);
	}
	
	/**
	 * 用post方法获取数据
	 * @param $url
	 * @param $data
	 * @return
	 */
	public function post_it($url, $data)
	{
		$curl = curl_init();
		curl_setopt($curl, CURLOPT_URL, $url);
		curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
		curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
		curl_setopt($curl, CURLOPT_POST, 1);
		curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
		$result = curl_exec($curl);
		if($result){
			curl_close($curl);
			return $result;
		}
		else {
			$error = curl_errno($curl);
			curl_close($curl);
			return false;
		}
	}
	
	public function cancel(){
		$this->display('cancel_code.html');
	}
	
	public function cancelCode(){
		$code = isset($_POST['codes'])?$_POST['codes']:"";
		if(!$code){
			$res = array("error"=>1,"content"=>"请输入Code值");
			$this->showMsg($res);
		}
		$access_token = Model('app')->getAccessToken();
		$url = "https://api.weixin.qq.com/card/code/get?access_token=".$access_token;
		$info['code'] = $code;
		$info['check_consume'] = false;
		$result = json_decode($this->post_it($url, json_encode($info)),true);
		if($result['errcode']!=0){
			$res = array("error"=>1,"content"=>"Code值有问题，请确认后再次输入");
			$this->showMsg($res);
		}
		if($result['can_consume']==0&&$result['user_card_status']!="NORMAL"){
			$res = array("error"=>1,"content"=>"请确认卡券状态后再次输入");
			$this->showMsg($res);
		}
		
		$cancel = "https://api.weixin.qq.com/card/code/consume?access_token=".$access_token;
		$post = array("code"=>$code,"card_id"=>$result['card']['card_id']);
		$resu = json_decode($this->post_it($cancel, json_encode($post)),true);
		if($resu['errcode']!=0){
				$res = array("error"=>1,"content"=>"核销卡券失败，请重新输入");
				$this->showMsg($res);
		}else{
			$res = array("error"=>0,"content"=>"核销卡券成功");
			$this->showMsg($res);
		}
	}
}

?>